const { getAliSTS,randomFileName } = require('./util')
const app = getApp()

const tokenWhiteListUrl = ['/wechatapp/openid','/wechatapp/phone','/wechatapp/login','/wechatapp/unionid']

// 超时时间设置成10分钟
const timeout = 600*1000

let hasShowError = false
let hadShowRequestError = false

async function requestFail(){
  console.log('request fail')
  wx.removeStorageSync('token')
  if(!hasShowError){
    hasShowError = true
    wx.showModal({
      title:'提示',
      content:'您还未登录或已过期，请先登录',
      showCancel:false,
      confirmText:'确定',
      success : async ()=>{

      },
      complete(){
        hasShowError = false
      }
    })
  }
}

function wxLogin(){
  return new Promise(resolve=>{
    wx.login({
      success:(res)=>{
        // console.log('login res:',res)
        if(res.code){
          // 发起网络请求，获取openId等信息
          let query = (wx.getLaunchOptionsSync()).query
          let reqData = {
            code:res.code
          }
          if(Object.keys(query).length > 0){
            reqData.inviteUserId = query.inviteUserId
            reqData.shareChannel = query.shareChannel
          }
          wx.request({
            url: app.globalData.url + '/wechatapp/unionid',
            data:reqData,
            method: 'POST',
            success: function (res) {
              // console.log('res:',res)
              if(res.data.code === 0){
                wx.setStorageSync('token',res.data.data.token)
                wx.setStorageSync('userId',res.data.data.userId)
                resolve(true)
              }else {
                resolve(false)
              }
            },
            fail(err){
              console.log('error:',err)
              resolve(false)
            }
          })
        }else {
          resolve(false)  
        }
        // console.log('login res:',res)
      },
      fail(error){
        console.log('登录失败：',error)
        resolve(false)
      }
    })
  })
  
}

function request(requestConfig) {
  let tempUrl = requestConfig.url

  if (!tempUrl.startsWith('http')) {
    tempUrl = app.globalData.url + tempUrl
  }
  let token = wx.getStorageSync('token')
  // console.log('token:',token)
  let header = requestConfig?.header || {'content-type':'application/json'}
  let inWhiteList = tokenWhiteListUrl.findIndex(url=>{
    return requestConfig.url.includes(url)
  })
  
  if (inWhiteList === -1 && token) {
    header['token'] = token
  }
  
  let requestTask = wx.request({
    method: requestConfig.method || 'GET',
    url: tempUrl,
    data: requestConfig.data,
    header: header,
    timeout:timeout,
    success(res) {
      if (res.data.respCode === 1) {
        requestConfig.success && requestConfig.success(res.data.respData,res.data)
      } else if(res.data.respCode === 401){
        console.log('401 res.data:',res.data)
        if(requestConfig.fail){
          requestConfig.fail(res.data)
        }else {
          requestFail()
        }
        
      } else {
        // console.log('request tempUrl:',tempUrl)
        // console.log('res.data:',res.data)
        if(requestConfig.fail){
          requestConfig.fail(res.data)
        }else {
          wx.showModal({
            title:'',
            content:res.data.respMsg,
            showCancel:false,
            confirmText:'确定'
          })
        }
      }
    },
    fail(error) {
      console.log('fail error:',error)
      if (requestConfig.fail) {
        requestConfig.fail(error)
      } else {
        
        if(!hadShowRequestError){
          hadShowRequestError = true
          let hasShowModalError = wx.getStorageSync('hasShowModalError') || false
          if(!hasShowModalError){
            wx.showModal({
              title: '',
              content: '您的网络断开了，请稍后再试',
              showCancel:false,
              confirmText:'确定',
            })
            wx.setStorageSync('hasShowModalError',true)
          }
          
        }
        
      }
    },
    complete() {
      requestConfig.complete && requestConfig.complete()
    }
  })
  return requestTask
}

// 上传到服务器，再由服务器上传到阿里云
function uploadFile(tempFilePath){
  let token = wx.getStorageSync('token')
  // console.log('tempFilePath:',tempFilePath)
  
  return new Promise((resolve)=>{
    wx.uploadFile({
      url:app.globalData.url+'/sys/oss-upload-media',
      filePath:tempFilePath,
      name:'file',
      timeout:timeout,
      header: {
        "Content-Type": "multipart/form-data",
        "token":token
      },
      success(res){
        // console.log('uploadFile res',res)
        
        if(res.data){
          // alert('res.data:'+res.data)
          let jsonData = JSON.parse(res.data)
          // console.log('upload jsonData:',jsonData)
          if(jsonData.code===0){
            resolve(jsonData.data)
          }else {
            wx.showModal({
              title: '',
              content: '上传失败，请稍后再试。'+JSON.stringify(jsonData),
              showCancel:false,
              confirmText:'确定'
            })
          }
          
        }
      },
      fail(error){
        console.log('uploadFile error:',error)
        // alert('uploadFile error:'+ JSON.stringify(error))
        wx.showModal({
          title: '',
          content: '上传文件失败，请稍后再试',
          showCancel:false,
          confirmText:'确定'
        })
      }
    })
  })
}
export async function getAliOssToken(){
  return new Promise((resolve)=>{
    request({
      url:'/api/sys/sts-assume-role',
      success(data){
        // console.log('getAliOssToken:',data)
        resolve(data)
      },
      fail(){
        resolve(false)
      }
    })
  })
  
}
// 本地直接上传到阿里云
export async function uploadFile2(tempFilePath){
  // console.log('uploadFile2:',tempFilePath)
  
  return new Promise(async resolve=>{
    let credentials = await getAliOssToken()
    // console.log('aliKey credentials:',credentials)
    let aliReqFormData = getAliSTS(credentials)
    // console.log('aliReqFormData:',aliReqFormData)
    let tempFileName = randomFileName()
    // console.log('tempFileName:',tempFileName)
    let extList = tempFilePath.split('.')
    let ext = extList[extList.length - 1]
    let fileName = tempFileName +'.'+ext
    let host = 'https://static.wanhuhealth.com'
    let fileUrl = host +'/wanhuhealth/media/'+ fileName
    // console.log('tempFilePath:',tempFilePath)
    // console.log('fileUrl:',fileUrl)
    wx.uploadFile({
      url:host,
      filePath:tempFilePath,
      name:'file',
      timeout:timeout,
      formData:{
        key:'wanhuhealth/media/'+fileName,
        ...aliReqFormData
      },
      success(res){
        // console.log('uploadFile res',res)
        if(res.statusCode === 204){
          // 上传成功
          resolve(fileUrl)
        }else {
          console.error(res)
          wx.showModal({
            title: '',
            content: '上传文件失败，请稍后再试',
            showCancel:false,
            confirmText:'确定'
          })
        }
      },
      fail(error){
        console.log('uploadFile error:',error)
        // alert('uploadFile error:'+ JSON.stringify(error))
        wx.showModal({
          title: '',
          content: '上传文件失败，请稍后再试',
          showCancel:false,
          confirmText:'确定'
        })
      }
    })
  })
  

}
module.exports = {
  getAliOssToken,
  request,
  uploadFile,
  uploadFile2,
  wxLogin
}
